import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_house_manager/api/house.dart';
import 'package:flutter_house_manager/pages/controller/build_controller.dart';
import 'package:flutter_house_manager/utils/cameraDialog.dart';
import 'package:flutter_house_manager/utils/toast.dart';
import 'package:get/get.dart' hide FormData, MultipartFile;
import 'package:image_picker/image_picker.dart';

class HouseForm extends StatefulWidget {
  const HouseForm({super.key, required this.id});
  final String? id;

  @override
  State<HouseForm> createState() => _HouseFormState();
}

class _HouseFormState extends State<HouseForm> {
  Map<String, dynamic> _formData = {
    'point': '', // 小区信息
    'building': '', // 小区楼栋信息
    'room': '', // 小区房间信息
    'name': '', // 业主姓名
    'gender': 1, // 业主性别0女1男
    'mobile': '', // 业主电话
    'idcardFrontUrl': '', // 身份证正面
    'idcardBackUrl': '', // 身份证背面
  };
  // 正面照/背面照文件名称
  String _frontName = '';
  String _backName = '';
  bool isLoading = false;
  String _editId = '';

  // 引入楼栋控制器
  BuildController buildController = Get.find<BuildController>();

  // 定义姓名和手机号控制器，ListView滑出可视区域没有指针指向的话，填写的内容会消失，因此绑定控制器
  TextEditingController nameController = TextEditingController();
  TextEditingController mobileController = TextEditingController();

  /// 上传图片到接口服务器, 得到图片的url地址
  uploadImage(String uri, String fileName) async {
    FormData data;
    if (kIsWeb) {
      Uint8List list = await XFile(uri).readAsBytes(); // 读取二进制
      // 要得到file对象
      MultipartFile file = MultipartFile.fromBytes(list, filename: fileName);
      data = FormData.fromMap({"file": file}); // 得到formData类型要进行上传
    } else {
      data = FormData.fromMap({"file": MultipartFile.fromFileSync(uri)});
    }
    final res = await uploadPhotoAPI(data);
    return res["url"]; // 上传成功的地址
  }

  // 提交表单
  _onSubmit() async {
    // 1. 校验输入的数据
    // 检查 小区 楼栋 和房间不能为空
    if ((_formData["point"] as String).isEmpty ||
        (_formData["building"] as String).isEmpty ||
        (_formData["room"] as String).isEmpty) {
      PromptAction.showError("小区楼栋房间信息不能为空");
      return;
    }
    if (_formData["name"].isEmpty) {
      PromptAction.showError("业主姓名不能为空");
      return;
    }
    if (!RegExp(r'^[\u4e00-\u9fa5]{2,10}').hasMatch(_formData["name"])) {
      PromptAction.showError("业主姓名为2-10个汉字");
      return;
    }
    if (_formData["mobile"].isEmpty) {
      PromptAction.showError("业主电话不能为空");
      return;
    }
    if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(_formData["mobile"])) {
      PromptAction.showError("业主电话格式不正确");
      return;
    }
    // 检查身份证照片是否上传
    if (_formData["idcardFrontUrl"].isEmpty ||
        _formData["idcardBackUrl"].isEmpty) {
      PromptAction.showError("请上传身份证照片");
      return;
    }
    // 判断图片地址中是否以http或者https开头
    // 正面照
    if (!_formData["idcardFrontUrl"].startsWith("http") &&
        !_formData["idcardFrontUrl"].startsWith("https")) {
      try {
        _formData["idcardFrontUrl"] =
            await uploadImage(_formData["idcardFrontUrl"], _frontName);
      } catch (e) {
        PromptAction.showError("上传图片失败");
        return;
      }
    }
    // 背面照
    if (!_formData["idcardBackUrl"].startsWith("http") &&
        !_formData["idcardBackUrl"].startsWith("https")) {
      try {
        _formData["idcardBackUrl"] =
            await uploadImage(_formData["idcardBackUrl"], _backName);
      } catch (e) {
        PromptAction.showError("上传图片失败");
        return;
      }
    }
    // 删除_formData中多余的属性
    _formData.removeWhere((key, value) => key == 'status');
    // 3. 提交数据
    try {
      await addHouseAPI(_formData);
      PromptAction.showSuccess(
          '${widget.id.toString().isEmpty ? '添加' : '修改'}成功');
      buildController.updateBuildInfo({'point': '', 'build': '', 'room': ''});
      Navigator.popUntil(context, (route) {
        return route.settings.name == '/';
      });
      Navigator.pushNamed(context, '/house_list');
    } catch (e) {
      PromptAction.showError("提交失败");
    }
  }

  /// 打开相册
  openLibrary(String tag) async {
    // 1. 创建一个选择图片的实例
    ImagePicker picker = ImagePicker();
    // 2. 调用方法打开相册
    // ImageSource.gallery 获取相册图片
    // ImageSource.camera 获取相机图片
    XFile? file = await picker.pickImage(source: ImageSource.gallery);
    // 3. 判断图片是否获取成功
    if (file != null) {
      // 4. 存储图片地址和名称
      if (tag == 'idcardFrontUrl') {
        _frontName = file.name;
      } else if (tag == 'idcardBackUrl') {
        _backName = file.name;
      }
      _formData[tag] = file.path;
      // 5. 刷新UI
      setState(() {});
      Navigator.of(context).pop();
    }
  }

  /// 如果有id参数，则说明是编辑房屋信息，则需要获取房屋信息
  getHouseDetail(String id) async {
    setState(() {
      isLoading = true;
    });
    final res = await getHouseDetailAPI(id);
    setState(() {
      isLoading = false;
    });
    nameController.text = res['name'];
    mobileController.text = res['mobile'];
    setState(() {
      _formData = res;
    });
  }

  // @override
  // void didChangeDependencies() {
  //   super.didChangeDependencies();
  //   // 1. 获取路由传递的参数
  //   final params = ModalRoute.of(context)?.settings.arguments as Map;
  //   if (params["id"] != null && params["id"] != "") {
  //     getHouseDetail(params["id"]);
  //   }
  // }

  @override
  void initState() {
    super.initState();
    // 1.收集小区信息
    _formData['point'] = buildController.buildInfo['point'];
    _formData['building'] = buildController.buildInfo['building'];
    _formData['room'] = buildController.buildInfo['room'];
    if (widget.id.toString().isNotEmpty) {
      _editId = widget.id.toString();
      setState(() {});
      getHouseDetail(widget.id.toString());
    }
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder(builder: (BuildController controller) {
      return Scaffold(
        appBar: AppBar(
          title: Text(_editId.isEmpty ? '添加房屋信息' : '修改房屋信息'),
          backgroundColor: Colors.transparent,
          centerTitle: true,
        ),
        body: isLoading
            ? const Center(
                child: CircularProgressIndicator(),
              )
            : ListView(
                padding: const EdgeInsets.only(top: 10, bottom: 10),
                children: [
                  // 房屋信息
                  Container(
                    padding: const EdgeInsets.all(10),
                    child: const Text(
                      '房屋信息',
                      style: TextStyle(
                          color: Color.fromARGB(255, 97, 94, 94), fontSize: 16),
                    ),
                  ),
                  Container(
                    color: Colors.white,
                    padding: const EdgeInsets.only(
                        left: 10, right: 10, top: 15, bottom: 15),
                    child: Text(
                        '${_formData['point']}${_formData['building']}${_formData['room']}室'),
                  ),
                  // 业主信息
                  Container(
                    padding: const EdgeInsets.all(10),
                    child: const Text(
                      '业主信息',
                      style: TextStyle(
                          color: Color.fromARGB(255, 97, 94, 94), fontSize: 16),
                    ),
                  ),
                  // 业主姓名
                  Container(
                    color: Colors.white,
                    padding: const EdgeInsets.only(left: 10, right: 10),
                    child: TextField(
                      controller: nameController,
                      onChanged: (value) {
                        _formData['name'] = value;
                      },
                      maxLength: 15,
                      decoration: const InputDecoration(
                        labelText: '姓名',
                        hintText: '请输入业主姓名',
                        hintStyle: TextStyle(color: Colors.grey),
                        border: InputBorder.none,
                      ),
                      inputFormatters: [
                        LengthLimitingTextInputFormatter(10),
                      ],
                    ),
                  ),
                  // 性别
                  Container(
                    color: Colors.white,
                    padding: const EdgeInsets.only(left: 10, right: 10),
                    child: Row(
                      children: [
                        const Text(
                          '性别',
                          style: TextStyle(fontSize: 16),
                        ),
                        const SizedBox(width: 20),
                        Radio(
                          value: 1,
                          groupValue: _formData['gender'],
                          onChanged: (value) {
                            setState(() {
                              _formData['gender'] = value ?? '';
                            });
                          },
                        ),
                        const Text('男'),
                        const SizedBox(width: 10),
                        Radio(
                          value: 0,
                          groupValue: _formData['gender'],
                          onChanged: (value) {
                            setState(() {
                              _formData['gender'] = value ?? '';
                            });
                          },
                        ),
                        const Text('女'),
                      ],
                    ),
                  ),
                  // 业主手机号
                  Container(
                    color: Colors.white,
                    padding: const EdgeInsets.only(left: 10, right: 10),
                    child: TextField(
                      controller: mobileController,
                      onChanged: (value) {
                        _formData['mobile'] = value;
                      },
                      keyboardType: TextInputType.phone,
                      maxLength: 11,
                      decoration: const InputDecoration(
                        labelText: '手机号',
                        hintText: '请输入您的手机号',
                        hintStyle: TextStyle(color: Colors.grey),
                        border: InputBorder.none,
                      ),
                      inputFormatters: [
                        LengthLimitingTextInputFormatter(11),
                      ],
                    ),
                  ),
                  // 业主信息
                  Container(
                    padding: const EdgeInsets.all(10),
                    child: const Text(
                      '本人身份证照片',
                      style: TextStyle(
                          color: Color.fromARGB(255, 97, 94, 94), fontSize: 16),
                    ),
                  ),
                  Container(
                    padding:
                        const EdgeInsets.only(left: 10, right: 10, bottom: 10),
                    child: const Text(
                      '请拍摄证件原件，并使照片中证件边缘完整，文字清晰，光线均匀。',
                      style: TextStyle(
                          color: Color.fromARGB(255, 97, 94, 94), fontSize: 12),
                    ),
                  ),
                  // 身份证正面
                  Container(
                    color: Colors.white,
                    height: 320,
                    padding: const EdgeInsets.all(10),
                    child: _formData['idcardFrontUrl'] == ''
                        ? _buildAddIdcardPhoto('idcardFrontUrl', '上传人像面照片')
                        : _buildIdcardPhoto(
                            'idcardFrontUrl',
                            _formData['idcardFrontUrl'],
                          ),
                  ),
                  const SizedBox(height: 20),
                  // 身份证反面
                  Container(
                    color: Colors.white,
                    height: 320,
                    padding: const EdgeInsets.all(10),
                    child: _formData['idcardBackUrl'] == ''
                        ? _buildAddIdcardPhoto('idcardBackUrl', '上传国徽面照片')
                        : _buildIdcardPhoto(
                            'idcardBackUrl',
                            _formData['idcardBackUrl'],
                          ),
                  ),
                  const SizedBox(height: 20),
                  // 提交审核
                  Container(
                    padding: const EdgeInsets.all(10),
                    child: ElevatedButton(
                      onPressed: () {
                        _onSubmit();
                      },
                      child: const Column(
                        children: [
                          SizedBox(height: 8),
                          Icon(Icons.exit_to_app),
                          Text('提交审核'),
                          SizedBox(height: 8)
                        ],
                      ),
                    ),
                  ),
                ],
              ),
      );
    });
  }

  Widget _buildAddIdcardPhoto(String tag, String info) {
    return GestureDetector(
      onTap: () {
        showCameraDialog(context, onLibrary: () {
          openLibrary(tag);
        });
      },
      child: const Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Icon(
            Icons.add,
            size: 30,
            color: Color.fromARGB(255, 85, 145, 175),
          ),
          Text(
            '上传人像面照片',
            style: TextStyle(
              color: Color.fromARGB(255, 85, 145, 175),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildIdcardPhoto(String tag, String photoUrl) {
    return Stack(children: [
      SizedBox(
        width: MediaQuery.of(context).size.width - 20,
        height: 300,
        child: kIsWeb ||
                photoUrl.startsWith('http') ||
                photoUrl.startsWith('https')
            ? Image.network(photoUrl, fit: BoxFit.contain)
            : Image.asset(photoUrl, fit: BoxFit.contain),
      ),
      Positioned(
        right: 0,
        top: 0,
        child: GestureDetector(
          child: const Icon(Icons.delete, color: Colors.red),
          onTap: () {
            setState(() {
              _formData[tag] = '';
            });
          },
        ),
      )
    ]);
  }
}
